package org.micode.libs.smon.utils;

import com.sun.management.OperatingSystemMXBean;
import org.micode.libs.smon.vo.MemoryInfo;

import java.lang.management.ManagementFactory;

public class MemoryUtils {

    public static MemoryInfo readMemory() {
        MemoryInfo info = new MemoryInfo();
        fillMemory(info);
        return info;
    }

    public static void fillMemory(MemoryInfo info) {
        if (null == info) {
            return;
        }

        OperatingSystemMXBean osmb = (OperatingSystemMXBean) ManagementFactory.getOperatingSystemMXBean();

        info.setTotalMemory(osmb.getTotalPhysicalMemorySize());
        info.setFreeMemory(osmb.getFreePhysicalMemorySize());
        info.setUsedMemory(info.getTotalMemory() - info.getFreeMemory());

        if (info.getTotalMemory() > 0) {
            info.setMemoryUsage(info.getUsedMemory() / (1.0 * info.getTotalMemory()));
        } else {
            info.setMemoryUsage(0);
        }

        info.setTotalSwap(osmb.getTotalSwapSpaceSize());
        info.setFreeSwap(osmb.getFreeSwapSpaceSize());
        info.setUsedSwap(info.getTotalSwap() - info.getFreeSwap());

        if (info.getTotalSwap() > 0) {
            info.setSwapUsage(info.getUsedSwap() / (1.0 * info.getTotalSwap()));
        } else {
            info.setSwapUsage(0);
        }
    }

}
